package wedaex.helper;

import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import wedaex.content.XmlComponent;

public class XmlHelper {
	private static DocumentBuilderFactory documentBuilderFactory;
	private static DocumentBuilder builder;
	private static TransformerFactory transformerFactory;
	private static Transformer transformer;

	static {
		try {
			documentBuilderFactory = DocumentBuilderFactory.newInstance();
			builder = documentBuilderFactory.newDocumentBuilder();

			transformerFactory = TransformerFactory.newInstance();
			transformer = transformerFactory.newTransformer();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		}
	}

	public static void writeXml(XmlComponent extractor, OutputStream output) {
		Document doc = builder.newDocument();
		Element element = doc.createElement("test");
		CDATASection cdata = doc.createCDATASection("some data");
		
		Element data = extractor.toXml(doc);
		doc.appendChild(data);
		try {
			transformer.transform(new DOMSource(doc), new StreamResult(output));
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}
}
